#include "widget.h"
#include "ui_widget.h"
#include <QPushButton>
#include "Herb.h"
#include <QRegularExpression>
#include "herbselecteddialog.h"



Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    initHerbs();

    initPills();

    setupButtons();

    connectSlots();

    ui->txtResult->setReadOnly(true);

    ui->medicine->setIconSize(QSize(100, 100)); // 设置丹药图标尺寸
    ui->medicine->setText("无");
    ui->medicine->setStyleSheet(
        "QPushButton {"
        "  border: 2px dashed #7f8c8d;" // 初始灰色边框
        "  color: #7f8c8d;"             // 初始灰色文字
        "}"
        );

}

void Widget::initPills()
{
    m_pillDatabase = {
        {"化瘀丹", {":/icons/images/huayudan.png", "基础修炼丹药\n需求：活血+1 培元+1"}},
        {"凝神丹", {":/icons/pill_mind.png", "提升神识丹药\n需求：凝神+2 固元+1"}},
        {"大还丹", {":/icons/pill_great.png", "疗伤圣药\n需求：活血+3 生息+2"}}
    };
}

void Widget::onHerbButtonClicked(QPushButton* targetBtn) {
    HerbSelectedDialog dlg(m_herbDatabase, this);

    if (dlg.exec() == QDialog::Accepted) {
        QString selectedherb = dlg.selectedHerb();
        updateButtonDisplay(targetBtn, selectedherb);
    }
}


Widget::EffectStats Widget::checkeff(const QList<HerbSelection>& selections) const
{
    QHash<QString, int> maineff, aideff;

    foreach (const auto& sel, selections) {
        auto effects = sel.herb.geteff(sel.role);
        if (sel.role == "主药") {
            for (auto it = effects.begin(); it != effects.end(); ++it) {
                maineff[it.key()] += it.value();
            }
        } else if (sel.role == "辅药") {
            for (auto it = effects.begin(); it != effects.end(); ++it) {
                aideff[it.key()] += it.value();
            }
        }
    }

    // 示例 根据实际需求修改
    bool valid = (maineff.value("活血", 0) >= 1) &&
                 (aideff.value("培元", 0) >= 1);

    return {maineff, aideff, valid}; // 返回结构体
}

void Widget::updateButtonDisplay(QPushButton* btn, const QString& herbName)
{

    if (herbName.isEmpty()) { // “无”选项会传递空字符串
        btn->setProperty("herbName", QVariant());
        btn->setIcon(QIcon());
        btn->setText("点击选择");
        btn->setToolTip("");
    }

    else if (m_herbDatabase.contains(herbName)) {
        const Herb& herb = m_herbDatabase[herbName];
        btn->setProperty("herbName", herbName);

        // 加载图标
        QPixmap pix(herb.iconPath());
        if (!pix.isNull()) {
            btn->setIcon(QIcon(pix.scaled(60, 60, Qt::KeepAspectRatio)));}

         btn->setText(herb.name());

        QString tooltip = QString("%1\n"
                                  "寒热值：%2\n"
                                  "主药效果：%3\n"
                                  "辅药效果：%4")
                              .arg(herb.name())
                              .arg(herb.thermal())
                              .arg(herb.getmaineff().join(", "))  // 使用新方法
                              .arg(herb.getaideff().join(", ")); // 使用新方法

        btn->setToolTip(tooltip);
    }
    else {
        // 清空选择
        btn->setProperty("herbName", QVariant());
        btn->setIcon(QIcon());
        btn->setText("点击选择");
        btn->setToolTip("");
    }



    QList<HerbSelection> selections = getCurrentSelections();
    int thermalSum = 0;
    foreach (const auto& sel, selections) {
        thermalSum += sel.herb.thermal();
    }
    bool thermalBalance = (thermalSum == 0);

    EffectStats stats = checkeff(selections);
    QHash<QString, int> maineff = stats.main;
    QHash<QString, int> aideff = stats.aid;
    bool effectValid = stats.isValid;

     QString targetPill = ui->medicine->text().split("：").last();

    QString resultText;
    QTextStream stream(&resultText);
    stream << "【验证结果】\n"
           << "寒热平衡: " << (thermalBalance ? "✔" : "✘ (差值: "
                                            + QString::number(thermalSum) + ")") << "\n"
           << "药性条件: " << (effectValid ? "✔" : "✘") << "\n"
           << "目标丹药: " << targetPill;

    ui->txtResult->setText(resultText);

    if (thermalBalance && effectValid) {
        // 成功状态
        ui->medicine->setIcon(QIcon(":/icons/pill_success.png"));
        ui->medicine->setText("炼制成功：" + targetPill);
        ui->medicine->setStyleSheet(
            "QPushButton {"
            "  border: 2px solid #27ae60;"
            "  color: #27ae60;"
            "  font-weight: bold;"
            "  padding: 10px;"
            "}");
    } else {
        // 失败状态
        ui->medicine->setIcon(QIcon());
        ui->medicine->setText("目标丹药：" + targetPill);
        ui->medicine->setStyleSheet(
            "QPushButton {"
            "  border: 2px dashed #e74c3c;"
            "  color: #e74c3c;"
            "  padding: 10px;"
            "}");
    }


    if (thermalBalance && effectValid) {

        QString pillName = "化瘀丹"; // 默认丹药名
        QString iconPath = ":/icons/images/huayudan.png"; // 默认图标

        // 示例判断逻辑（根据实际需求扩展）


        // 2. 设置图标和文字
        QPixmap pillPix(iconPath);
        if (!pillPix.isNull()) {
            ui->medicine->setIcon(QIcon(pillPix.scaled(80, 80, Qt::KeepAspectRatio)));
        }

        // 3. 设置复合显示样式
        ui->medicine->setText(pillName);
        ui->medicine->setStyleSheet(
            "QPushButton {"
            "  border: 2px solid #27ae60;"
            "  color: #27ae60;"
            "  font-weight: bold;"
            "  padding: 8px;"
            "  qproperty-iconSize: 80px;" // 控制图标尺寸
            "  background-color: rgba(39,174,96,0.1);" // 浅绿色背景
            "}"
            );

    } else {
        // 失败状态显示
        ui->medicine->setIcon(QIcon());
        ui->medicine->setText("");
        ui->medicine->setStyleSheet(
            "QPushButton {"
            "  border: 2px dashed #e74c3c;"
            "  color: #e74c3c;"
            "  padding: 10px;"
            "  background-color: rgba(231,76,60,0.1);" // 浅红色背景
            "}"
            );
    }
}



Widget::~Widget()
{
    delete ui;
}

void Widget::initHerbs(){
    m_herbDatabase={
        {"恒心草",Herb("恒心草",0,{{"聚元",1}},{{"养气",1}},":/icons/images/hengxincao.png")},
        {"宁心草",Herb("宁心草",-1,{{"振气",1}},{{"清心",1}},":/icons/images/ningxincao.png")},
        {"天青花",Herb("天青花",+1,{{"活血",1}},{{"凝神",1}},":/icons/images/tianqinghua.png")},
        {"银月花",Herb("银月花",-1,{{"活血",1}},{{"固元",1}},":/icons/images/yinyuehua.png")},
        {"凝血草",Herb("凝血草",0,{{"生息",1}},{{"混元",1}},":/icons/images/ningxuecao.png")},
        {"流莹草",Herb("流莹草",+1,{{"生息",1}},{{"培元",1}},":/icons/images/liuyingcao.png")},
        {"宁神花",Herb("宁神花",-1,{{"无",1}},{{"宁神",1}},":/icons/images/ningshenhua.png")},
    };
}

void Widget::setupButtons()
{
    // 配置按钮通用属性
    QString buttonStyle =
        "QPushButton {"
        "  border: 2px solid #3498db;"
        "  border-radius: 8px;"
        "  padding: 10px;"
        "  font-size: 12px;"
        "  min-width: 90px;"
        "}"
        "QPushButton:hover {"
        "  background-color: #f0f8ff;"
        "}";

    // 获取所有药材按钮
    QList<QPushButton*> herbButtons = findChildren<QPushButton*>(
        QRegularExpression("(main1|main2|aid1|aid2|guide)")
        );

    foreach (QPushButton* btn, herbButtons) {
        btn->setStyleSheet(buttonStyle);
        btn->setIconSize(QSize(60, 60));
        btn->setText("点击选择");
        btn->setProperty("herbName", QVariant());
    }
}

void Widget::connectSlots()
{
    // 连接所有药材选择按钮
    QList<QPushButton*> buttons = findChildren<QPushButton*>(
        QRegularExpression("(main1|main2|aid1|aid2|guide)")
        );

    foreach (QPushButton* btn, buttons) {
        connect(btn, &QPushButton::clicked, this, [=](){
            onHerbButtonClicked(btn);
        });
    }
}


void Widget::onStartAlchemy()
{
    // 收集所有选中的药材
    QList<HerbSelection> selections = getCurrentSelections();

    // 执行验证逻辑
    int thermalSum = 0;
    foreach (const auto& sel, selections) {
        thermalSum += sel.herb.thermal();
    }
    bool thermalBalance = (thermalSum == 0);

    EffectStats stats = checkeff(selections);
    bool effectValid = stats.isValid;


    // 显示结果
    QString resultText;
    resultText += QString("寒热平衡：%1\n")
                      .arg(thermalBalance ? "✔" : "✘");
    resultText += QString("药性合格：%1\n")
                      .arg(effectValid ? "✔" : "✘");

    ui->txtResult->setText(resultText);
}

QList<Widget::HerbSelection> Widget::getCurrentSelections() const
{
    QList<HerbSelection> selections;

    // 获取所有药材按钮
    QList<QPushButton*> buttons = findChildren<QPushButton*>(
        QRegularExpression("(main1|main2|aid1|aid2|guide)")
        );

    foreach (QPushButton* btn, buttons) {
        QString herbName = btn->property("herbName").toString();
        if ((!herbName.isEmpty()) && m_herbDatabase.contains(herbName)) {
            selections << HerbSelection{
                .herb = m_herbDatabase[herbName],
                .role = parseRole(btn->objectName()),
                .position = parsePosition(btn->objectName())
            };
        }
    }
    return selections;
}

bool Widget::checkThermalBalance(const QList<HerbSelection>& selections) const
{
    int thermalSum = 0;
    foreach (const auto& sel, selections) {
        thermalSum += sel.herb.thermal();
    }
    return thermalSum == 0;
}



QString Widget::parseRole(const QString& objectName) const
{
    if (objectName.startsWith("main1")||objectName.startsWith("main2")) return "主药";
    if (objectName.startsWith("aid1")||objectName.startsWith("aid2")) return "辅药";
    if (objectName.startsWith("guide")) return "药引";
    return "";
}

int Widget::parsePosition(const QString& objectName) const
{
    // 从对象名中提取位置编号，如btnMain1 → 1
    QRegularExpression re("\\d+");
    QRegularExpressionMatch match = re.match(objectName);
    return match.hasMatch() ? match.captured().toInt() : 0;
}

